/******************************************************************************
 * Copyright (C) 2016  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#ifndef NODE_SYSTEM_MUTEX_WIN32_H_
#define NODE_SYSTEM_MUTEX_WIN32_H_

#define WIN32_MEAN_AND_LEAN
#include <Windows.h>
#include <node/noncopyable.h>

namespace node {
    namespace system {

        class mutex_impl : private noncopyable
        {
        public:
            mutex_impl(void);
            ~mutex_impl(void);

            bool lock_impl(void);
            bool trylock_impl(void);
            void unlock_impl(void);

        private:
            CRITICAL_SECTION _cs;
        };

        inline mutex_impl::mutex_impl(void)
        {
            ::InitializeCriticalSectionAndSpinCount(&_cs, 4000);
        }
        inline mutex_impl::~mutex_impl(void)
        {
            ::DeleteCriticalSection(&_cs);
        }

        inline bool mutex_impl::lock_impl(void)
        {
            ::EnterCriticalSection(&_cs);
            return true;
        }
        inline bool mutex_impl::trylock_impl(void)
        {
            return (::TryEnterCriticalSection(&_cs) == TRUE);
        }
        inline void mutex_impl::unlock_impl(void)
        {
            ::LeaveCriticalSection(&_cs);
        }

}}

#endif //NODE_SYSTEM_MUTEX_WIN32_H_
